package com.kaifamiao.context;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 1、ServletContext是什么
 *    There is one context per "web application" per Java Virtual Machine.
 *    每个JVM中的每个 "Web应用" 都对应着一个ServletContext实例。
 *
 * 2、ServletContext的作用
 *    Defines a set of methods that a servlet uses to communicate with its servlet container。
 *    定义了servlet用来与其servlet容器通信的一组方法。
 *    即 servlet 通过 ServletContext实例 与 容器进行通信。
 */
@WebServlet("/app/*")
public class ApplicationServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // There is one context per "web application" per Java Virtual Machine.
        final ServletContext application = this.getServletContext();
        // 获得Servlet上下文名称
        String name = application.getServletContextName();
        out.printf( "<p>context name: %s</p>\n", name );

        // 获得Servlet上下文路径(即当前Web应用路径)
        String path = application.getContextPath();
        out.printf( "<p>context path: %s</p>\n", path );

        // 获得当前Web应用中指定路径在磁盘上的真实路径
        String realPath = application.getRealPath("/WEB-INF");
        out.printf( "<p>/WEB-INF real path: %s</p>\n", realPath );
    }

}
